﻿using System;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;

namespace HealthCommunity.Controls
{
	public partial class UCQuestionDetail : System.Web.UI.UserControl
	{
		private IQuestionProvider _QuestionProvider;

		public int QuestionID
		{
			get
			{
				return CommonHelper.QueryStringInt("questionid");
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindQuestion();
			}
		}

		protected void btnSubmitAnswer_Click(object sender, EventArgs e)
		{
			if(!string.IsNullOrEmpty(txtAnswerQuestion.Text.Trim()))
			{
				var user = SiteContext.Current.CurrentUser;
				if(user != null)
				{
					var theAnswer = new Answer() { AnswerTime = DateTime.Now, QuestionID = QuestionID, AnswerContent = txtAnswerQuestion.Text.Trim(), AnswerUserID = user.UserID };

					if(_QuestionProvider == null)
					{
						_QuestionProvider = new QuestionProvider();
					}

					if(_QuestionProvider.CreateAnswer(theAnswer) != null)
					{
						BindQuestion();
					}
				}
			}
		}

		protected void rptAnswer_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if(e.Item.DataItem != null)
			{
				var dataItem = e.Item.DataItem as Answer;

				var ltrAnswerContent = e.Item.FindControl("ltrAnswerContent") as Literal;
				var ltrAnswerUser = e.Item.FindControl("ltrAnswerUser") as Literal;
				var ltrAnswerTime = e.Item.FindControl("ltrAnswerTime") as Literal;

				ltrAnswerContent.Text = dataItem.AnswerContent;
				ltrAnswerUser.Text = "回答人:" + dataItem.User.UserCName;
				ltrAnswerTime.Text = "回答时间" + dataItem.AnswerTime.GetValueOrDefault().ToString();
			}
		}

		private void BindQuestion()
		{
			if(QuestionID > 0)
			{
				if(_QuestionProvider == null)
				{
					_QuestionProvider = new QuestionProvider();
				}

				var theQuestion = _QuestionProvider.GetQuestion(QuestionID);

				if(theQuestion != null)
				{
					this.ltrQuestionContent.Text = theQuestion.QuestionContent;
					this.ltrRewardScore.Text = theQuestion.RewardScores.GetValueOrDefault(0).ToString();
					this.ltrQuestionUser.Text = theQuestion.User.UserCName;
					if(theQuestion.Answers != null && theQuestion.Answers.Count > 0)
					{
						ltrAnswers.Text = "回答数: " + theQuestion.Answers.Count.ToString();
					}
					else
					{
						ltrAnswers.Text = "回答数: 0";
					}
					this.ltrQuestionHits.Text = "点击数: " + theQuestion.QuestionHits.GetValueOrDefault(0).ToString();
					this.ltrRewardScore.Text = "奖励积分: " + theQuestion.RewardScores.GetValueOrDefault(0).ToString();
					this.ltrAddTime.Text = "提问时间: " + theQuestion.QuestionAddTime.GetValueOrDefault().ToString();

					rptAnswer.DataSource = _QuestionProvider.GetAnswerByQuestion(QuestionID);
					rptAnswer.DataBind();
				}
			}
		}
	}
}